package yt.kpool.fragment;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;



import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yt.kpool.R;

import yt.kpool.adapter.SimpleSecondAdapter;
import yt.kpool.base.BaseApplication;
import yt.kpool.bean.HomeListBean;
import yt.kpool.bean.MinerModelDetailsBean;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.SPUtil;

import yt.kpool.util.Util;
import yt.kpool.util.imageUtil.GlideUtil;
import yt.kpool.view.HeaderProductSecondLayout;
import yt.kpool.view.dialog.LoadingDialog;

import yt.kpool.view.pop.HomeSelectThreePop;
import yt.kpool.view.pop.HomeSelectTwoPop;

@SuppressLint("ValidFragment")
public class HomeSecondAFg  extends Fragment {
    private HeaderProductSecondLayout mHeaderView;
    @BindView(R.id.main_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.ly_top)
    LinearLayout ly_top;

    @BindView(R.id.ly_top2)
    LinearLayout ly_top22;
    @BindView(R.id.ly_top3)
    LinearLayout ly_top33;

    @BindView(R.id.tv_2)
    TextView tv_2;
    @BindView(R.id.tv_3)
    TextView tv_3;

    @BindView(R.id.iv_2)
    ImageView iv_2;
    @BindView(R.id.iv_3)
    ImageView iv_3;
    private HomeSelectTwoPop homeSelectTwoPop;
    private HomeSelectThreePop homeSelectThreePop;
    private SPUtil spUtil;
    boolean isfresh,isdownfresh;
    private String flash_p="0.27";
    private int kind;
    private int imageY = 0;
    private LinearLayout ly_top2,ly_top3,ly_tops,ly_changes;
    private TextView tv_22,tv_33,tv_c1s,tv_c2s,tv_c3s;
    private ImageView iv_22,iv_33;
    private int pricekind=2;
    private int mToPosition;
    private boolean mShouldScroll;
    private SimpleSecondAdapter simpleAdapter;
    private List<MinerModelDetailsBean.DataBean.CoinListBean> listData=new ArrayList<>();
    private MinerModelDetailsBean minerModelDetailsBean;

    @SuppressLint("ValidFragment")
    public HomeSecondAFg(MinerModelDetailsBean minerModelDetailsBean)
    {
        super();
        this.minerModelDetailsBean = minerModelDetailsBean;

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_homeseconda, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }



    /**
     *初始化数据
     */
    private void init()
    {
        if (spUtil == null)
            spUtil = new SPUtil(getContext(), "fileName");
        if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1)
        {
            flash_p="0.27";

            kind=1;
        }
        else if(spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2)
        {
            flash_p="0.040";

            kind=2;
        }

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        mHeaderView = new HeaderProductSecondLayout(getContext());

        ly_top2 = mHeaderView.findViewById(R.id.ly_top2);
        ly_top3 = mHeaderView.findViewById(R.id.ly_top3);


          tv_22= mHeaderView.findViewById(R.id.tv_2);
          tv_33= mHeaderView.findViewById(R.id.tv_3);
          iv_22= mHeaderView.findViewById(R.id.iv_2);
          iv_33= mHeaderView.findViewById(R.id.iv_3);
          ly_tops=mHeaderView.findViewById(R.id.ly_top);
          ImageView imageview=mHeaderView.findViewById(R.id.imageview);
          GlideUtil.loadImages(getContext(), NetHelperNew.URL + minerModelDetailsBean.getData().getImage(), imageview);
          listData=minerModelDetailsBean.getData().getCoinList();

          simpleAdapter = new SimpleSecondAdapter(getContext(),listData);
          simpleAdapter.addHeaderView(mHeaderView);
          mRecyclerView.setAdapter(simpleAdapter);
          simpleAdapter.setExchange(minerModelDetailsBean.getData().getExchange());
          simpleAdapter.setKind(kind,Double.valueOf(flash_p));
          sort(2);
          simpleAdapter.notifyDataSetChanged();
          mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int[] location = new int[2];
                ly_top.getLocationOnScreen(location);
                int y = location[1];
                imageY = y;
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mHeaderView == null) return;
                int getTop = mHeaderView.getDistanceY();
                if (getTop <= imageY) {
                    ly_top.setVisibility(View.VISIBLE);
                } else {
                    ly_top.setY(0);
                    ly_top.setVisibility(View.GONE);
                }
            }
        });

        initPop();

        /**
         * 顶部第二个筛选条件
         */
        ly_top2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectStyle(2,true);
                smoothMoveToPosition(mRecyclerView, 1);
                new Handler().postDelayed(new Runnable(){
                    public void run(){
                        //execute the task
                        if(homeSelectThreePop.isShowing())
                        {
                            homeSelectThreePop.dismiss();
                        }
                        homeSelectTwoPop.showAsDropDown(ly_top2, 0, 0);

                    }
                },200);
            }
        });
        /**
         * 顶部第三个筛选条件
         */
        ly_top3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectStyle(3,true);
                smoothMoveToPosition(mRecyclerView, 1);
                new Handler().postDelayed(new Runnable(){
                    public void run(){
                        //execute the task
                        if(homeSelectTwoPop.isShowing())
                        {
                            homeSelectTwoPop.dismiss();
                        }
                        homeSelectThreePop.showAsDropDown(ly_top2, 0, 0);
                    }
                },200);
            }
        });


    }

    /**
     * 点击事件的处理
     *
     * @param view
     */
    @OnClick({R.id.ly_top2, R.id.ly_top3})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ly_top2:
                selectStyle(2,true);

                if(homeSelectThreePop.isShowing())
                {
                    homeSelectThreePop.dismiss();
                }
                homeSelectTwoPop.showAsDropDown(ly_top22, 0, 0);
                break;
            case R.id.ly_top3:
                selectStyle(3,true);

                if(homeSelectTwoPop.isShowing())
                {
                    homeSelectTwoPop.dismiss();
                }
                homeSelectThreePop.showAsDropDown(ly_top22, 0, 0);
                break;

        }
    }

    /**
     * 初始化pop数据
     */
    private void initPop() {

        homeSelectTwoPop = new HomeSelectTwoPop(getActivity(), new HomeSelectTwoPop.OnSelectItemListener() {
            @Override
            public void select(int i,String name) {
                flash_p=name;
                if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1)
                {
                    tv_2.setText(name+"¥/度");
                    tv_22.setText(name+"¥/度");
                }
                else if(spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2)
                {

                    tv_2.setText(name+"$/度");
                    tv_22.setText(name+"$/度");
                }
                if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1)
                {
                    simpleAdapter.setKind(1,Double.valueOf(name));
                    simpleAdapter.notifyDataSetChanged();
                }
                else if(spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2)
                {
                    simpleAdapter.setKind(2,Double.valueOf(name));
                    simpleAdapter.notifyDataSetChanged();
                }

                smoothMoveToPosition(mRecyclerView, 1);
            }
        },2);

        if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1)
        {
            homeSelectTwoPop.setKind(1);
            tv_2.setText("0.27¥/度");
            tv_22.setText("0.27¥/度");
        }
        else if(spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2)
        {
            homeSelectTwoPop.setKind(2);
            tv_2.setText("0.040$/度");
            tv_22.setText("0.040$/度");
        }
        homeSelectThreePop = new HomeSelectThreePop(getActivity(), new HomeSelectThreePop.OnSelectItemListener() {
            @Override
            public void select(int i,String name) {

                if(name.equals("最赚钱"))
                {
                    pricekind=2;
                    sort(2);
                }
                else
                {
                    pricekind=1;
                    sort(1);
                }
                simpleAdapter.notifyDataSetChanged();
                smoothMoveToPosition(mRecyclerView, 0);
                tv_3.setText(name);
                tv_33.setText(name);
            }
        });
        /**
         * 第一个pop关闭时的监听
         */

        /**
         * 第二个pop关闭时的监听
         */
        homeSelectTwoPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                selectStyle(2,false);
            }
        });
        /**
         * 第三个pop关闭时的监听
         */
        homeSelectThreePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                selectStyle(3,false);
            }
        });
    }
    /**
     * 选择pop时的样式
     * @param n
     * @param b
     */
    private void selectStyle(int n,boolean b)
    {


        if(n==2)
        {

            if(b)
            {
                ly_top22.setBackgroundResource(R.drawable.lable_corner_bg);
                tv_2.setTextColor(getActivity().getResources().getColor(R.color.system_color));
                iv_2.setImageResource(R.mipmap.icon_up);

                ly_top2.setBackgroundResource(R.drawable.lable_corner_bg);
                tv_22.setTextColor(getActivity().getResources().getColor(R.color.system_color));
                iv_22.setImageResource(R.mipmap.icon_up);

            }
            else
            {
                ly_top22.setBackgroundResource(R.drawable.lable_corners_bg);
                tv_2.setTextColor(getActivity().getResources().getColor(R.color.home_top_word));
                iv_2.setImageResource(R.mipmap.icon_down);

                ly_top2.setBackgroundResource(R.drawable.lable_corners_bg);
                tv_22.setTextColor(getActivity().getResources().getColor(R.color.home_top_word));
                iv_22.setImageResource(R.mipmap.icon_down);

            }

        }

        else if(n==3)
        {
            if(b)
            {
                ly_top33.setBackgroundResource(R.drawable.lable_corner_bg);
                tv_3.setTextColor(getActivity().getResources().getColor(R.color.system_color));
                iv_3.setImageResource(R.mipmap.icon_up);

                ly_top3.setBackgroundResource(R.drawable.lable_corner_bg);
                tv_33.setTextColor(getActivity().getResources().getColor(R.color.system_color));
                iv_33.setImageResource(R.mipmap.icon_up);
            }
            else
            {
                ly_top33.setBackgroundResource(R.drawable.lable_corners_bg);
                tv_3.setTextColor(getActivity().getResources().getColor(R.color.home_top_word));
                iv_3.setImageResource(R.mipmap.icon_down);

                ly_top3.setBackgroundResource(R.drawable.lable_corners_bg);
                tv_33.setTextColor(getActivity().getResources().getColor(R.color.home_top_word));
                iv_33.setImageResource(R.mipmap.icon_down);

            }

        }
    }
    /**
     * 排序
     */
    private void sort(final int kind)
    {
        for(int i=0;i<listData.size();i++)
        {
            BigDecimal c1 = new BigDecimal(listData.get(i).getCurrencyPrice());
            BigDecimal c2 = new BigDecimal(BaseApplication.Exchange);
            String cp1=c1.multiply(c2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+"";

            BigDecimal b1 = new BigDecimal(listData.get(i).getThroughput());
            BigDecimal b2 = new BigDecimal(cp1);
            String sp1=b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+"";

            BigDecimal bb1 = new BigDecimal(listData.get(i).getPower());
            BigDecimal bb2 = new BigDecimal(Util.NMultiplication(0.024+"",flash_p));
            String sp2=bb1.multiply(bb2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+"";

            BigDecimal bbb1 = new BigDecimal(sp1);
            BigDecimal bbb2 = new BigDecimal(sp2);
            String sp3=bbb1.subtract(bbb2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+"";

            listData.get(i).setIncome(Double.valueOf(sp3));


        }


        Collections.sort(listData, new Comparator<MinerModelDetailsBean.DataBean.CoinListBean>() {

            @Override
            public int compare(MinerModelDetailsBean.DataBean.CoinListBean o1, MinerModelDetailsBean.DataBean.CoinListBean o2) {

                if(kind==1) // 最赚钱的
                {
                    if (o1.getIncome() > o2.getIncome()) {
                        return 1;
                    }
                    if (o1.getIncome() == o2.getIncome()) {
                        return 0;
                    }
                    return -1;
                }
                else//最不赚钱的
                {
                    if (o1.getIncome() > o2.getIncome()) {
                        return -1;
                    }
                    if (o1.getIncome() == o2.getIncome()) {
                        return 0;
                    }
                    return 1;
                }

            }
        });
    }
    /**
     * RecyclerView 判断滚动距离
     * @param mRecyclerView
     * @param position
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {

        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {

            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {

            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                if(ly_top.getHeight()==0)
                    mRecyclerView.smoothScrollBy(0, top-ly_tops.getHeight());
                else
                    mRecyclerView.smoothScrollBy(0, top-ly_top.getHeight());
            }
        } else {

            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }
}
